# 视图文件
from FlaskPro.OA.models import db, Position, Person, Department, News,Attendance,Permission
from FlaskPro.OA import oa
from flask import request, render_template
from .forms import UserForm
from .forms import AddPersonForm

from flask import redirect
from flask import make_response
from flask import session

import os
import functools
import hashlib
def setpassword(pwd):
    md5 = hashlib.md5()
    md5.update(pwd.encode())
    result = md5.hexdigest()
    return result

# 权限验证
@oa.add_app_template_global
def check_perm():
    result = {
        # False 代表没有权限
        "news":False,
        "ex":False,
        "renshi":False
    }
    """----------根据职位进行权限校验--------------"""
    userid = request.cookies.get("userid")
    userid = int(userid)
    person = Person.query.get(userid)
    # 新闻管理：董事长，人事拥有权限    判断部门是否是人事部门
    # 人事管理：人事，董事长拥有权限
    login_pos = person.our_position
    login_dep = login_pos.p_depart.d_name
    if login_dep == "人事部":
        result["news"] = True
        result["renshi"] = True
    #
    # 权限管理：董事长拥有
    #
    # 考勤管理（下属考勤）：董事长，职级大于1的可以查看
    # 判断登录用户职级
    if login_pos.p_level > 1:
        result["ex"] = True
    #   董事长
    if login_pos.p_level == 5:
        result = {
            "news": True,  # False 代表没有权限
            "ex": True,
            "renshi": True
        }

    """---------根据权限和职位的关系进行校验-----------"""
    # userid = request.cookies.get("userid")
    # # userid = int(userid)
    # person = Person.query.get(userid)
    # pos = person.our_position
    # # 判断该职位是否拥有权限
    # # 新闻管理
    # news_perm = Permission.query.filter(Permission.per_name == "新闻管理").first()
    # news_pos = news_perm.p_position  # 列表
    # if pos in news_pos:
    #     result["news"] = True
    return result

def LoginVolid(func):
    @functools.wraps(func)  #保留原有的函数名字
    def inner(*args,**kwargs):
        session_username = session.get("username")
        userid = request.cookies.get("userid")
        cookie_username = request.cookies.get("username")
        if session_username and userid and cookie_username:
            person = Person.query.filter(
                Person.id == int(userid),
                Person.username == session_username
            ).first()
            if person:
                return func(*args,**kwargs)
        return redirect("/login")
    return inner

@oa.route("/")
@LoginVolid
def home():
    return render_template("index.html")

@oa.route("/login",methods=["GET","POST"])
def login():
    if  request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        # 校验数据
        if password and username:
            # 查询数据
            person = Person.query.filter(Person.username == username,Person.password == setpassword(password)).first()
            if person:
                #下发cookie和session
                resp = redirect("/")
                resp.set_cookie("userid",str(person.id))
                resp.set_cookie("username",person.username)
                resp.set_cookie("nickname",person.nickname)
                session["username"] = person.username
                return resp
    return render_template("login.html", **locals())

@oa.route("/logout")
def logout():
    # 删除cookie和session
    resp = redirect("/login")
    resp.delete_cookie("userid")
    resp.delete_cookie("username")
    del session["username"]
    return resp

@oa.route("/register",methods = ["GET","POST"])
def register():
    userform = UserForm()
    if request.method == "POST":
        data = request.form
        print(data)
        if UserForm.validate_on_submit():  #将提交的数据，交给forms类进行后端校验
            print("sucess")
            data = userform.data  #获取校验之后的数据，结果为字典
            username = data.get("username")
            password = data.get("password")
            print(data)
        else:
            print("error")
            errors = userform.errors
            print(errors)
    return render_template("register.html",**locals())

@oa.route("/index")
def index():
    return render_template("index.html", **locals())

@oa.route("/demoapi")
def demoapi():
    result = {
        "data":[]
    }
    dep_list = Department.query.all()
    for dep in dep_list:
        dep_person_num = 0   # 每个部门下面的人数
        # 查询每个部门下的人数
        # 部门 ——》职位 ——》人数（求和）
        pos_list = dep.d_position
        for pos in pos_list:
            person_num = len(pos.p_person)   #某个职位下面的人数
            print(pos.p_person)
            dep_person_num += person_num
        result_dict = {
            "name":dep.d_name,
            "num":dep_person_num
        }
        result["data"].append(result_dict)
    return result

@oa.route("/news")
def news():
    new_list = News.query.all()
    print(new_list)
    return render_template("news.html", **locals())

import datetime
@oa.route("/add_news",methods = ["GET","POST"])
def add_news():
    news = News()
    img = request.files.get('picture')
    if request.method == "POST":
        news.n_name = request.form.get("title")
        news.n_author = request.form.get("author")
        news.n_date = datetime.datetime.now()
        news.n_content = request.form.get("content")
        if img:
            # 拼接路径，
            img_name = img.filename
            db_path = os.path.join("images", img_name)
            file_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            static_path = os.path.join(file_path, "static")
            save_path = os.path.join(static_path, db_path)
            # 保存图片，
            img.save(save_path)
            # 对象属性赋值
            news.n_picture = db_path
        news.save()
        return redirect("/news")
    return render_template("add_news.html", **locals())

@oa.route("/edit_news/<int:id>",methods = ["GET","POST"])
def edit_news(id):
    news = News.query.filter(News.id == id).first()
    if request.method == "POST":
        img = request.files.get('picture')
        news.n_name = request.form.get("title")
        news.n_author = request.form.get("author")
        news.n_date = request.form.get("content")
        if img:
            # 拼接路径，
            img_name = img.filename
            db_path = os.path.join("images", img_name)
            file_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            static_path = os.path.join(file_path, "static")
            save_path = os.path.join(static_path, db_path)
            # 保存图片，
            img.save(save_path)
            news.n_picture = db_path
        news.update()
        return redirect("/news")
    return render_template("edit_news.html", **locals())

@oa.route("/detail_news/<int:id>")
def detail_news(id):
    news = News.query.filter(News.id == id).first()
    return render_template("detail_news.html", **locals())

@oa.route("/del_news/<int:id>")
def del_news(id):
    news = News.query.filter(News.id == id).first()
    news.delete()
    return redirect("/news")

@oa.route("/permission")
def permission():
    perm_list = Permission.query.all()
    return render_template("permission.html", **locals())

@oa.route("/add_permission",methods = ["GET","POST"])
def add_permission():
    if request.method == "POST":
        perm = Permission()
        perm.per_name = request.form.get("name")
        perm.per_desc = request.form.get("description")
        perm.save()
        return redirect("/permission")
    return render_template("add_permission.html", **locals())

@oa.route("/delete_permission/<int:id>")
def delete_permission(id):
    perm = Permission.query.filter(Permission.id == id).first()
    perm.delete()
    return redirect("/permission")

@oa.route("/edit_permission/<int:id>",methods = ["GET","POST"])
def edit_permission(id):
    perm = Permission.query.filter(Permission.id == id).first()
    if request.method == "POST":
        perm = Permission.query.filter(Permission.id == id).first()
        perm.per_name = request.form.get("name")
        perm.per_desc = request.form.get("description")
        perm.update()
        return redirect("/permission")

    return render_template("edit_permission.html", **locals())

@oa.route("/position_permission/<int:id>",methods = ["GET","POST"])
def position_permission(id):
    # 获取所有的权限
    perm = Permission.query.filter(Permission.id == id).first()
    # 获取所有的职位
    pos_list = Position.query.all()
    if request.method == "POST":
        # print(request.form)
        # 获取要关联的职位
        position_ids = request.form.getlist("position_ids")
        perm.p_position = [Position.query.get(int(i)) for i in position_ids]
        perm.save()
        return redirect("/permission")

    return render_template("position_permission.html", **locals())

@oa.route("/attendance_me",methods = ["GET","POST"])
@LoginVolid
def attendance_me():
    userid  = int(request.cookies.get("userid"))
    person = Person.query.filter(Person.id == userid).first()

    if request.method == "POST":
        attendance = Attendance()
        attendance.reason = request.form.get("reason")
        attendance.a_type = request.form.get("type")
        attendance.days = request.form.get("day")
        attendance.start_time = datetime.datetime.strptime(request.form.get("start"),"%Y-%m-%d %H:%M:%S")
        attendance.end_time = datetime.datetime.strptime(request.form.get("end"),"%Y-%m-%d %H:%M:%S")
        # 申请人
        attendance.user = person.id
        """-----------人事部门审核开始-----------"""
        # # 审核人
        # # 人事部人员
        # dep = Department.query.filter(Department.d_name == "人事部").first()
        # # pos = dep.d_position  #  列表
        # pos = Position.query.filter(Position.p_level==1,
        #                             Position.p_department == dep.id).first()
        # # 查询人事部门下的人员
        # ex_user = Person.query.filter(Person.p_position == pos.id).first()
        # print(pos)
        # ad.examine = ex_user.username
        """---------人事部门结束---------"""

        """------部门领导审核------"""
        # # 查询登录用户所在的职位中比自己职级高的用户
        # # 查询到登录用户的职级
        # pos = person.our_position
        # pos_level = pos.p_level
        # dep = pos.p_depart
        # # 查询该部门下的职级  + 1 的用户
        # ex_level = pos_level +1
        # ex_pos = Position.query.filter(Position.p_level == ex_level,
        #                                Position.p_department ==dep.id
        #                                ).first()
        # print(ex_pos)
        # ex_person = Person.query.filter(Person.p_position == ex_pos.id).first()
        #
        #
        # ad.examine = ex_person.username
        """------部门领导结束------"""
        attendance.examine = ""
        attendance.save()
    attendance_list = Attendance.query.all()
    return render_template("attendance_me.html", **locals())

@oa.route("/attendance_subordinate")
@LoginVolid
def attendance_subordinate():
    userid = int(request.cookies.get("userid"))  #登陆用户的id
    # 通过userid ——》登录用户 ——》职位 ——》职级小于登陆用户的并且同一个部门的所有人——》所有下属 ——》下属考勤
    person = Person.query.filter(Person.id == userid).first()
    # 登陆用户职位
    pos = person.our_position
    pos_level = pos.p_level
    dep_id = pos.p_department
    # 下属的所有职位
    lower_pos_list = Position.query.filter(Position.p_level < pos_level,Position.p_department == dep_id).all()
    # 所有的考勤信息返回
    Ad_list = []
    # 查询 职员
    for lower in lower_pos_list:
        lower_person = lower.p_person  # 下属人员列表
        for one in lower_person:
            #每一个下属的考勤列表
            ad_list = Attendance.query.filter(Attendance.user == one.id).all()
            #将一个列表中的元素添加到另一个列表
            Ad_list.extend(ad_list)

    return render_template("attendance_subordinate.html", **locals())

@oa.route("/update_attendance_subordinate/<int:status>/<int:id>")
@LoginVolid
def update_attendance_subordinate(status,id):
    # 假条id
    ad = Attendance.query.filter(Attendance.id == id).first()
    ex_userid = int(request.cookies.get("userid"))   #审核人的id
    person = Person.query.filter(Person.id == ex_userid).first()

    if status == 1:
        # 通过
        ad.status = 1
    elif status == 2:
        # 驳回
        ad.status = 2
    ad.examine = person.username
    ad.save()
    return redirect("/attendance_subordinate")

@oa.route("/department")
def department():
    department_list = Department.query.all()
    return render_template("department.html", **locals())

@oa.route("/add_department",methods=["GET","POST"])
def add_department():
    department = Department()
    if request.method == "POST":
        department.d_name = request.form.get("name")
        department.d_description = request.form.get("description")
    # if request.method == "POST":
    #     for key,value in request.form.items():
    #         if hasattr(department,key):
    #             setattr(department,key,value)
        department.save()
        return redirect("/department")
    return render_template("add_department.html", **locals())

@oa.route("/edit_department/<int:id>",methods=["GET","POST"])
def edit_department(id):
    department = Department.query.filter(Department.id == id).first()
    if request.method == "POST":
        department.d_name = request.form.get("name")
        department.d_description = request.form.get("description")
        department.update()
        return redirect("/department")
    return render_template("edit_department.html", **locals())

@oa.route("/del_department/<int:id>")
def del_department(id):
    department = Department.query.filter(Department.id == id).first()
    department.delete()
    return redirect("/department")

@oa.route("/position",methods = ["GET","POST"])
def position():
    position_list = Position.query.all()
    dep_id = request.args.get("dep_id")  #部门id
    if request.method == "POST":
        position = Position()
        position.p_name = request.form.get("name")

    return render_template("position.html", **locals())

@oa.route("/add_position",methods=["GET","POST"])
def add_position():
    dep_id = request.args.get("dep_id")  # 部门id
    if request.method == "POST":
        position = Position()
        position.p_name = request.form.get("name")
        position.p_level = request.form.get("level")
        position.p_department = dep_id
        position.save()
        return redirect("/position")

@oa.route("/edit_position",methods = ["GET","POST"])
def edit_position():
    dep_id = request.args.get("dep_id")  # 部门id
    if request.method == "POST":
        position = Position()
        position.p_name = request.form.get("name")
        position.p_level = request.form.get("level")
        position.p_department = dep_id
        position.update()
    # return redirect("/position")

@oa.route("/del_position/<int:id>")
def del_position(id):
    position = Position.query.filter(Position.id == id).first()
    position.delete()
    return redirect("/position")

@oa.route("/person")
def person():
    # # 返回用户信息
    # person_list = Person.query.all()

    # 获取请求参数
    page = request.args.get("page")
    if page is None:
        page = 1
    else:
        page = int(page)
    dep_list = Department.query.all()
    page_size = 10
    person_obj = Person.query.paginate(page,page_size)
    person_username = request.args.get("person_username")
    if person_username:
        person_obj = Person.query.filter(Person.nickname.like("%%%s%%"%person_username)).paginate(page,page_size)
    person_list = person_obj.items
    start = page - 2
    if page <= 3:
        start = 1
        end = start + 5
    elif page >= person_obj.pages - 2:
        start = person_obj.pages - 4
        end = person_obj + 1
    else:
        start = page -2
        end = page + 3
    page_list = range(start,end)
    return render_template("person.html", **locals())

@oa.route("/add_person",methods=['POST','GET'])
def add_person():
    # 处理get请求 返回一个form表单
    # 处理post请求 提交数据
    addpersonform = AddPersonForm()
    if request.method == "POST":
        # 后端校验
        if addpersonform.validate_on_submit():
            data = addpersonform.data
            print(data)
            # # 判断用户名不能重复
            # username = request.form.get("username")
            # user = Person.query.filter(Person.username == username).first()
            # if user is None:
            # post请求
            # # 获取图片信息
            img = request.files.get('photo')
            # 接收数据 保存数据
            person = Person()
            person.username = request.form.get("username")
            person.password = request.form.get("password")
            person.nickname = request.form.get("nickname")
            person.age = request.form.get("age")
            person.gender = request.form.get("gender")
            if img:
                img_name = img.filename
                db_path = os.path.join("images",img_name)
                file_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
                static_path = os.path.join(file_path,"static")
                save_path = os.path.join(static_path,db_path)
                img.save(save_path)
                person.photo = db_path
            person.email = request.form.get("email")
            person.address = request.form.get("address")
            person.p_position = 1
            person.save()
            # 重新回到 用户页面
            # 重定向
            return redirect("/person")
        else:
            errors = addpersonform.errors
            print(errors)
    return render_template("add_person.html", **locals())

@oa.route("/edit_person/<int:id>",methods=['GET','POST'])
def edit_person(id):
    img = request.files.get('photo')
    person = Person.query.filter(Person.id == id).first()
    if request.method == "POST":
        for key,value in request.form.items():
            if hasattr(person,key):
                setattr(person,key,value)
        if img:
            # 拼接路径，
            img_name = img.filename
            db_path = os.path.join("images",img_name)
            file_path = os.path.dirname(os.path.abspath(__file__))
            static_path = os.path.join(file_path,"static")
            save_path = os.path.join(static_path,db_path)
            # 保存图片，
            img.save(save_path)
            # 对象属性赋值
            person.photo = db_path
        person.save()
        # data = request.form
        # person = Person(**data)
        # person.save()

        # username = request.form.get("username")
        # password = request.form.get("password")
        # nickname = request.form.get("nickname")
        # gender = request.form.get("gender")
        # age = request.form.get("age")
        # email = request.form.get("email")
        # if img:
        #     img_name = img.filename
        #     db_path = os.path.join("images", img_name)
        #     file_path = os.path.dirname(os.path.abspath(__file__))
        #     static_path = os.path.join(file_path, "static")
        #     save_path = os.path.join(static_path, db_path)
        #     img.save(save_path)
        #     person.photo = db_path
        # address = request.form.get("address")
        # score = request.form.get("score")
        # position = request.form.get("position_id")
        # person.username = username
        # person.password = password
        # person.nickname = nickname
        # person.gender = gender
        # person.age = age
        # person.email = email
        # # person.photo = img
        # person.address = address
        # person.score = score
        # person.position = position
        # person.update()
        return redirect("/person")
    return render_template("edit_person.html", **locals())

@oa.route("/detail_person/<int:id>",methods=['GET','POST'])
def detail_person(id):
    person = Person.query.filter(Person.id == id).first()
    return render_template("detail_person.html", **locals())

@oa.route("/del_person/<int:id>")
def del_delete(id):
    person = Person.query.filter(Person.id == id).first()
    person.delete()
    return redirect("/person")

@oa.route("/profile")
def profile():
    userid = request.cookies.get("userid")
    # print(userid)
    person = Person.query.filter(Person.id == int(userid)).first()
    return render_template("profile.html", **locals())

# @oa.route("/reqtest")
# def reqtest():
#     # 加入测试数据
#     # 加入部门
#     # dep = Department(d_name="测试部门",d_description="测试部门描述")
#     # dep.save()
#     #
#     # # 加入position数据
#     # pos = Position(p_name="测试职位",p_level=1,p_department=dep.id)
#     # pos.save()
#
#     # 加入职员
#     # 第一种
#     # person = Person(username="admin",password="111111",p_position=1)
#     # person.save()
#     # 第二种
#     # pos = Position.query.filter(Position.p_name=="测试",).first()
#     # person = Person(username="admin",password="111111",p_position=pos.id)
#     # person.save()
#     # 第三种
#     # pos = Position.query.filter(Position.p_name=="测试",).first()
#     # for i in range(1,20):
#     #     per = Person(username="admin{}".format(i),password="123456",our_position=pos)
#     #     per.save()
#     return "req请求"

@oa.route("/cookietest")
def cookietest():
    # 设置cookie
    resp = make_response("hello word")
    resp.set_cookie("name","zhangsan",max_age=120)
    # 删除cookie
    # resp.delete_cookie("name")
    return resp

@oa.route("/sessions")
def sessions():
    session["name"] = "张三李四和王五"
    return "设置session"

@oa.route("/getsessions")
def getsessions():
    data = session["name"]
    data = session.get("name")
    return "获取session"

@oa.route("/delsessions")
def delsessions():
    del session["name"]
    return "删除session"

# @oa.route("/add_data/")
# def add_data():
#     ## 添加部门 开始
#     dep_list = ["财务部", "市场部", "技术部", "人事部", "后勤部", "安保部", "法务部", "董事长"]
#     pos_list = {"总监":3,"主任":2,"职员":1}
#     for one in dep_list:
#         dep = Department()
#         dep.d_name = one
#         dep.d_description = "%s职能描述" %one
#         dep.save()
#     ## 添加职位
#         if one != "董事长":
#             for key,value in pos_list.items():
#                 pos = Position()
#                 pos.p_name = "%s-%s" %(one,key)
#                 pos.p_level = value
#                 pos.p_department = dep.id
#                 pos.save()
#     return "添加数据"
#
# from pypinyin import lazy_pinyin ## 汉字转拼音的库
# import random
# @oa.route("/add_person1/")
# def add_person1():
#     first_name = """敬森·邱晓蕴·邱旭晨·邱梓旋·邱诗芙·邱启儒·邱靖蒙·邱靖鑫·邱浩永·邱麒均·邱允泓·邱鹤元·邱梦韵·邱澍辰·邱恺宇·邱偌惜·邱蔚怡·邱灵辉·邱靓秋·邱灿荣·邱伊玲·邱薇琪·邱鹏祎·邱森宁·邱雅彤·邱宇煦·邱归旷·邱梦焓·邱冰清·邱琬芸·邱秦欧·邱忆博·邱轩晗·邱天筠·邱之阳·邱铭萱·邱小婷·邱淑霏·邱修泽·邱恩翔·邱如祎·邱丁茕·邱锦蓉·邱培乐·邱毅晖·邱代姗·邱绪和·邱元兴·邱奇颖·邱歆巧·邱义桦·邱守仁·邱川凯·邱一州·邱诺鑫·邱江静·邱喻安·邱孟博·邱怡盈·邱焱皓""".split("·邱")
#     last_name = "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨"
#     ## 职员列表
#     position_list = Position.query.filter(Position.p_level == 1).all()
#
#     for i in last_name:
#         for j in first_name:
#             name = i + j
#             username = "".join(lazy_pinyin(name))
#             p = Person()
#             p.username = username
#             p.password = "e10adc3949ba59abbe56e057f20f883e"
#             p.nickname = name
#             p.our_position = random.choice(position_list)
#             p.save()
#     return "保存完成"








































